/**
 * @file my-data.js
 * @author Yuvv
 * @date 2018/1/5
 */

function getPaginationNav(current, total, navCount, callback) {
  function getLi(num, txt, active, click) {
    active = active || false;
    txt = txt || num;
    var li = $('<li></li>');
    if (active) {
      li.addClass('active');
    }
    //fsch time:12-21 11:20
    var a = $('<a  href="'+Urls.resolve('storage:my_template') + '#' + num + '">' + txt + '</a>');
    a.click(function () {
      click(num);
    });
    li.append(a);
    return li;
  }

  function aroundCurrent(current, total, navCount) {
    var pages = [current];
    var halfNavCount = Math.ceil(navCount / 2);
    var minPage = Math.max(0, current - halfNavCount);
    var maxPage = Math.min(total + 1, current + halfNavCount);
    for (var i = current - 1; i > minPage; i--) {
      pages.unshift(i);
    }
    for (var j = current + 1; j < maxPage; j++) {
      pages.push(j);
    }

    if (pages.length < Math.min(navCount, total)) {
      if (maxPage - current < halfNavCount) {
        minPage = Math.max(0, maxPage - navCount - 1);
        for (i = pages[0] - 1; i > minPage; i--) {
          pages.unshift(i);
        }
      } else if (current - minPage < halfNavCount) {
        maxPage = Math.min(total + 1, minPage + navCount + 1);
        for (j = pages[pages.length - 1] + 1; j < maxPage; j++) {
          pages.push(j);
        }
      }
    }

    return pages;
  }

  navCount = navCount || 5;
  var nav = $('<nav></nav>'),
    ul = $('<ul class="pagination"></ul>');
  var pages = aroundCurrent(current, total, navCount);
  pages.forEach(function (value) {
    ul.append(getLi(value, value, value === current, callback));
  });
  if (current > 1) {
    ul.prepend(getLi(current - 1, '<i class="fa fa-angle-double-left"></i>', false, callback));
  }
  if (current < total) {
    ul.append(getLi(current + 1, '<i class="fa fa-angle-double-right"></i>', false, callback))
  }
  nav.append(ul);

  return nav;
}

function getDataMetaPanel(dm) {
  // dm.quantity = dm.quantity || 'N/A';
  dm.abstract = dm.abstract || 'N/A';
  dm.category = dm.category || 'N/A';
  dm.doi = dm.doi || 'N/A';
  dm.purpose = dm.purpose || 'N/A';
  var times=dm.add_time.split('.')[0].split('T');
  var add_time=times[0]+' '+times[1];
  return '<div class="panel panel-default">' +
    '  <div class="panel-heading">' +
    '    <a target="_blank" href="' + Urls.resolve('storage:show_data', {did: dm.id}) + '" title="' + gettext('View') + '">' + dm.title + '</a>' +
    '    <div class="pull-right">' +
    '      <a target="_blank" href="' + Urls.resolve('storage:add_data') + '?action=modify&did=' + dm.id + '" role="button" title="' + gettext('Edit') + '"><i class="fa fa-pencil"></i></a>' +
    '      <a role="button" onclick="deleteData(\'' + dm.id + '\',this)" title="' + gettext('Delete') + '"><i class="fa fa-trash"></i></a>' +
    '      <a target="_blank" href="' + Urls.resolve('storage:show_data', {did: dm.id}) + '" title="' + gettext('View') + '"><i class="fa fa-external-link"></i></a>' +
    '    </div>' +
    '  </div>' +
    '  <div class="panel-body">' +
    '    <div class="row">' +
    '      <div class="col-sm-12">' +
    '        <p><span class="dt">' + gettext('Add Time') + '</span><span class="dd">' + add_time + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '    <div class="row">' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Views') + '</span><span class="dd">' + dm.views + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Downloads') + '</span><span class="dd">' + dm.downloads + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Score') + '</span><span class="dd">' + dm.score + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '    <div class="row">' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Material Class') + '</span><span class="dd">' + dm.category_name + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Abstract') + '</span><span class="dd">' + dm.abstract + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">DOI</span><span class="dd">' + dm.doi + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Purpose') + '</span><span class="dd">' + dm.purpose + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '  </div>' +
    '</div>';
}

function getData(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('storage_api_v1:my_metadata'), {
    'page':page,
  }).done(function (resp) {
    $("#datameta-count").html(resp.data.count);
    var dmScope = $('#dm-scope');
    dmScope.empty();
    resp.data.results.forEach(function (it) {
      dmScope.append(getDataMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#dm-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getData(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getDataSort(page, perPage,isAsc) {
  var url='storage_api_v1:my_metadata_des';
  if(isAsc)
    url='storage_api_v1:my_metadata_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var dmScope = $('#dm-scope');
    dmScope.empty();
    resp.data.results.forEach(function (it) {
      dmScope.append(getDataMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#dm-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getDataSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function deleteData(did, that) {
  var panel = $(that).parents('.panel:first');
  $.showModal({
    title: gettext('Warning'),
    message: interpolate(gettext('Are you sure to delete "%s"'), [panel.find('.panel-heading').text()]),
    onOk: function () {
      $.ajax(Urls.resolve('storage_api_v1:metadata_detail', {pk: did}), {
        method: 'DELETE'
      }).done(function () {
        panel.hide(500, function () {
          panel.remove();
        });
      });
    }
  });
}

function getTemplatePanel(t) {
  t.category = t.category || 'N/A';
  var times=t.pub_date.split('.')[0].split('T');
  var pub_date=times[0]+' '+times[1];
  return '<div class="panel panel-' + (t.published ? 'default' : 'warning') + '">' +
    '  <div class="panel-heading">' +
    '    <a target="_blank" href="' + Urls.resolve('storage:template') + '?action=view&tid=' + t.id + '" title="' + gettext('View') + '">' + t.title + '</a>' +
    '    <div class="pull-right">' +
    '      <a target="_blank" href="' + Urls.resolve('storage:template') + '?action=modify&tid=' + t.id + '" role="button" title="' + gettext('Edit') + '"><i class="fa fa-pencil"></i></a>' +
    '      <a role="button" onclick="deleteTemplate(\'' + t.id + '\',this)" title="' + gettext('Delete') + '"><i class="fa fa-trash"></i></a>' +
    '      <a target="_blank" href="' + Urls.resolve('storage:template') + '?action=view&tid=' + t.id + '" title="' + gettext('View') + '"><i class="fa fa-external-link"></i></a>' +
    '    </div>' +
    '  </div>' +
    '  <div class="panel-body">' +
    '    <div class="row">' +
    '         <div class="col-sm-4">' +
    '           <p><span class="dt">' + gettext('Material Category') + '</span><span class="dd">' + t.category_name + '</span></p>' +
    '         </div>' +
    '      <div class="col-sm-4">' +
    '        <p><span class="dt">' + (t.published ? gettext('Publish Date') : gettext('Publish State')) + '</span>' +
    '           <span class="dd">' + (t.published ? pub_date : gettext('Unpublished')) + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-4">' +
    '        <p><span class="dt">' + gettext('Data Count') + '</span><span class="dd">' + t.ref_count + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '    <div class="row">' +
    '      <div class="col-sm-12">' +
    '        <p><span class="dt">' + gettext('Abstract') + '</span><span class="dd">' + t.abstract + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '  </div>' +
    '</div>';
}

function getTemplate(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('storage_api_v1:my_template'), {
    'page':page,
  }).done(function (resp) {
    $("#template-count").html(resp.data.count);
    var tScope = $('#t-scope');
    tScope.empty();
    resp.data.results.forEach(function (it) {
      tScope.append(getTemplatePanel(it));
    }
    );
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $tScope = $('#t-pagination-scope');
      $tScope.empty();
      $tScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getTemplate(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getTemplateSort(page, perPage,isAsc) {
  var url='storage_api_v1:my_template_des';
  if(isAsc)
    url='storage_api_v1:my_template_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var tScope = $('#t-scope');
    tScope.empty();
    resp.data.results.forEach(function (it) {
      tScope.append(getTemplatePanel(it));
    }
    );
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $tScope = $('#t-pagination-scope');
      $tScope.empty();
      $tScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getTemplateSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function deleteTemplate(tid, that) {
  var panel = $(that).parents('.panel:first');
  $.showModal({
    title: gettext('Warning'),
    message: interpolate(gettext('Are you sure to delete "%s"'), [panel.find('.panel-heading').text()]),
    onOk: function () {
      $.ajax(Urls.resolve('storage_api_v1:template_detail', {pk: tid}), {
        method: 'DELETE'
      }).done(function () {
        panel.hide(500, function () {
          panel.remove();
        });
      });
    }
  });
}
//数据调用函数
// function acquire_result(callback, query_type = 1, time_sort, page = 1) {
//   $.requestJSON({
//     url: Urls.resolve('storage_api_v1:dataset_list'),
//     method: 'GET',
//     param: {query_type: query_type, time_sort: time_sort, page: page},
//     onSuccess(data) {
//       console.log(data);
//       callback(data);
//     }
//     //如果获取不成功怎么办
//   });
// }
//
// function dataset_count(data) {
//   $("#dataset-count").text(data.data.count);
// }
//
// function dataset_set_table_noValue(data) {
//   $("#dataset_result").text(gettext("Nothing......"));
// }
//
// function dataset_set_table_hasValue(data) {
//   // $("#table-value").val(data.data.datasets[0].filename);
//   $("#dataset_result").empty();
//   var obj =
//     '      <table class="table-content" width="95%" border="0" align="center" cellspacing="0" cellpadding="8">\n' +
//     '        <tr class="tr-title"  align="left">\n' +
//     '          <td class="td-title-1 first">#</td>\n' +
//     '          <td class="td-title-2 second">' + gettext('Title') + '</td>\n' +
//     '          <td class="td-title-3 third">' + gettext('Author') + '</td>\n' +
//     '          <td class="td-title-4 fourth">' + gettext('Purpose') + '</td>\n' +
//     '          <td class="td-title-5 fifth">' + gettext('Number of uses') + '</td>\n' +
//     '          <td class="td-title-6 sixth">' + gettext('Options') + '</td>\n' +
//     '        </tr>';
//   var currentPage = data.data.current_page;
//   var numberOfPages = data.data.total_pages;
//   var step = (currentPage - 1) * numberOfPages;
//   $.each(data.data.results, function () {
//     step++;
//     var obj2 =
//       '        <ul class="list-inline">' +
//       '          <li><a role="button" id="" title="' + gettext('Delete') + '"><i class="fa fa-trash-o"></i></a></li>';
//     if (this['is_public'])
//       obj2 += '<li><a role="button" class="go_to_private" title="' + gettext('Private') + '"><i class="fa fa-eye"></i></a></li></ul>';
//     else
//       obj2 += '<li><a role="button" class="go_to_public" title="' + gettext('Public') + '"><i class="fa fa-eye-slash"></i></a></li></ul>';
//     obj +=
//       '        <tr class="tr-body" align="left" id="' + this['id'] + '">\n' +
//       '          <td class="td-body-1 first">' + step + '</td>\n' +
//       '          <td class="td-body-2 second">' + this['title'] + '</td>\n' +
//       '          <td class="td-body-3 third">' + this['author'] + '</td>\n' +
//       '          <td class="td-body-6 sixth">' + this['purpose'] + '</td>\n' +
//       '          <td class="td-body-7 seventh">' + this['ref_count'] + '</td>\n' +
//       '          <td class="td-body-8 eigthth">' + obj2 + '</td>\n' +
//       '        </tr>';
//   });
//   obj += '</table>';
//   $("#dataset_result").append(obj);
//
//   $(".tr-body:even").hover(function () {
//     $(this).css("background-color", "#DCDCDC");
//   }, function () {
//     $(this).css("background-color", "#F5F5F5");
//   });
//   $(".tr-body:odd").hover(function () {
//     $(this).css("background-color", "#DCDCDC");
//   }, function () {
//     $(this).css("background-color", "#FFFFFF");
//   });
//
//   $(document).on("click", ".go_to_private", function () {
//     $(this).attr({"class": "go_to_public", "title": gettext("公开")});
//     $(this).find("i").attr("class", "fa fa-eye-slash");
//     obj = $(this).parent().parent().parent().parent();
//     // alert(obj.prop('id'));
//     // var dataset_id1=obj.attr("id");
//   });
//   $(document).on("click", ".go_to_public", function () {
//     $(this).attr({"class": "go_to_private", "title": gettext("隐藏")});
//     $(this).find("i").attr("class", "fa fa-eye");
//     obj = $(this).parent().parent().parent().parent();
//     // alert(obj.prop('id'));
//   });
//
//   $(".tr-body").on('click', function () {
//     var dataset_id = $(this).attr("id");
//     window.open(Urls.resolve('management:show_data', {dataset_id: dataset_id, query_type: 1}));
//   });
// }
//
// function dataset_show_all(query_type, time_sort) {
//   acquire_result(function (data) {
//     dataset_count(data);
//     if (data.data.count == 0) {
//       dataset_set_table_noValue(data);
//     }
//     else {
//       dataset_set_table_hasValue(data);
//       var paginator = $('#dataset_paginator');
//       var options = {
//         bootstrapMajorVersion: 3,
//         currentPage: 1,
//         numberOfPages: 5,
//         totalPages: data.data.total_pages,
//         onPageClicked: function (e, originalEvent, type, page) {
//           acquire_result(dataset_set_table_hasValue, query_type, time_sort, page);
//         }
//       };
//       if (options.totalPages > 1) {
//         paginator.bootstrapPaginator(options);  // 仅大于一页时分页
//       }
//     }
//   }, query_type, time_sort, page = 1)
// }

function getDataSetPanel(ds) {
  ds.title = ds.title || '';
  ds.author = ds.author || '';
  ds.purpose = ds.purpose || '';
  return '<div class="panel panel-default">' +
    '  <div class="panel-heading">' +
    '    <a target="_blank" href="' + Urls.resolve('storage:view_dataset', {did: ds.id}) + '" id="' + gettext('View') + '">' + ds.id + '</a>' +
    '    <div class="pull-right">' +
    // '      <a target="_blank" href="' + Urls.resolve('storage:upload_dataset') + '?action=modify&did=' + ds.id + '" role="button" title="' + gettext('Edit') + '"><i class="fa fa-pencil"></i></a>' +
    '      <a role="button" onclick="deleteDataset(\'' + ds.id + '\',this)" title="' + gettext('Delete') + '"><i class="fa fa-trash"></i></a>' +
    '      <a target="_blank" href="' + Urls.resolve('storage:view_dataset', {did: ds.id}) + '" title="' + gettext('View') + '"><i class="fa fa-external-link"></i></a>' +
    '    </div>' +
    '  </div>' +
    '  <div class="panel-body">' +
    '    <div class="row">' +
    '      <div class="col-sm-12">' +
    '        <p><span class="dt">' + gettext('Title') + '</span><span class="dd">' + ds.title + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '    <div class="row">' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Author') + '</span><span class="dd">' + ds.author + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Purpose') + '</span><span class="dd">' + ds.purpose + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Number of use') + '</span><span class="dd">' + ds.ref_count + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '  </div>' +
    '</div>';
}

function getDataset(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('storage_api_v1:my_dataset'), {
    'page':page,
  }).done(function (resp) {
    var dsScope = $('#ds-scope');
    $("#dataset-count").html(resp.data.count);
    dsScope.empty();
    resp.data.results.forEach(function (it) {
      dsScope.append(getDataSetPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $dScope = $('#ds-pagination-scope');
      $dScope.empty();
      $dScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getDataset(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getDatasetSort(page, perPage,isAsc) {
  var url='storage_api_v1:my_dataset_des';
  if(isAsc)
    url='storage_api_v1:my_dataset_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var dsScope = $('#ds-scope');
    dsScope.empty();
    resp.data.results.forEach(function (it) {
      dsScope.append(getDataSetPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $dScope = $('#ds-pagination-scope');
      $dScope.empty();
      $dScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getDatasetSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function deleteDataset(did, that) {
  var panel = $(that).parents('.panel:first');
  $.showModal({
    title: gettext('Warning'),
    message: interpolate(gettext('Are you sure to delete "%s"'), [panel.find('.panel-heading').text()]),
    onOk: function () {
      $.ajax(Urls.resolve('storage_api_v1:dataset_detail', {pk: did}), {
        method: 'DELETE'
      }).done(function () {
        panel.hide(500, function () {
          panel.remove();
        });
      });
    }
  });
}

$(function () {
  var data = $('#data'), templates = $('#templates'), dataset = $('#dataset');
  getData(1, 5);
  if (templates.length > 0) {
    getTemplate(1,5);
  }
  getDataset(1,5);

  $("#data-time-forward").click(function () {
    getDataSort(1,5,true);
  });
  $('#data-time-reverse').click(function () {
    getDataSort(1,5,false);
  });
  $("#template-time-forward").click(function () {
    getTemplateSort(1,5,true);
  });
  $('#template-time-reverse').click(function () {
    getTemplateSort(1,5,false);
  });
  $("#dataset-time-forward").click(function () {
    getDatasetSort(1,5,true);
  });
  $('#dataset-time-reverse').click(function () {
    getDatasetSort(1,5,false);
  });
});
